package com.margo.project.socket.websocket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * 模拟WebSocket请求
 * @author fangxingbang
 * https://www.cnblogs.com/fuqiang88/p/5956363.html
 */
public class WebSocketClient {
	public static void main(String[] args) {
		/**
		 * websocket报文
		 * 	基于http协议
		 * Upgrade: websocket
		 * Connection: Upgrade
		 * 
		 */
		try {
		    String host = "localhost";
		    int port = 8080;
		    Socket socket = new Socket();
		    InetSocketAddress address=new InetSocketAddress(host, port);
		    socket.connect(address,10000); 
		    OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream(),"utf-8");
		    
		    osw.write("GET /websocket/demo HTTP/1.1\r\n");
		    osw.write("Host: localhost:8080\r\n");
		    osw.write("Connection: Upgrade\r\n");
		    osw.write("Pragma: no-cache\r\n");
		    osw.write("Cache-Control: no-cache\r\n");
		    osw.write("User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36\r\n");
		    osw.write("Upgrade: websocket\r\n");
		    osw.write("Origin: file://\r\n");
		    osw.write("Sec-WebSocket-Version: 13\r\n");
		    osw.write("Accept-Encoding: gzip, deflate, br\r\n");
		    osw.write("Accept-Language: zh-CN,zh;q=0.9\r\n");
		    osw.write("Cookie: _isLogout=false; cs_cStorage_=1; access-token=eyJhbGciOiJIUzUxMiJ9.eyJhY2NvdW50IjoiU3VwZXJBZG1pbiIsInVzZXJJZCI6IlN1cGVyQWRtaW4iLCJlbXBsb3llZUlkIjoiU3VwZXJBZG1pbiIsImVtcGxveWVlTmFtZSI6Iui2hee6p-euoeeQhuWRmCIsIm9yZ0lkIjoiMCIsIm9yZ0NvZGUiOiIwMyIsIm9yZ05hbWUiOiLlub_kuJznlLXnvZHlhazlj7giLCJzdWIiOiLotoXnuqfnrqHnkIblkZgiLCJpYXQiOjE1NDI4NTA4NzQsImV4cCI6MTU0Mjg1MjY3NCwicmVmcmVzaEludGVydmFsIjozMCwianRpIjoiYzcyNzMwYWUtZWEyYy00Yjk4LTg5YjEtMWMzOTJjZTAwMDMyIn0.QsCc_zYemZ15Whr_cZqM2H3s5UtOpTZpElW_bCBWgqB6qmG0JFl2TEHyvWCteBtxcE3NL9XrGTiWPjGNqGBE2g\r\n");
		    osw.write("Sec-WebSocket-Key: QyFhlRJqNGrg/eQMc9HnWw==\r\n");
		    osw.write("Sec-WebSocket-Extensions: client_max_window_bits\r\n");
		    osw.write("\r\n");
		    osw.flush();
		    socket.shutdownOutput();
		    BufferedReader bufferedReader = new BufferedReader(
		            new InputStreamReader(socket.getInputStream(), "utf-8"));
		    String line = null;
		    while ((line = bufferedReader.readLine()) != null) {
		        System.out.println(line);
		    }
		    osw.close();
		    bufferedReader.close();
		    socket.close();		
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
